/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.refunite.mobile.s60.ui;

import org.refunite.mobile.s60.RefugeesUnited;
import org.refunite.mobile.s60.persistence.PersistenceStoreProvider;
import org.refunite.mobile.s60.widget.AbstractFormWidget;
import org.refunite.mobile.s60.util.FormController;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

/**
 * @author I040022
 */
public class CollectScreen implements CommandListener, ItemCommandListener {

    //<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
    private Form CollectDataForm;
    private Command backCommand;
    //</editor-fold>//GEN-END:|fields|0|


    private RefugeesUnited midlet;

    private Command nextFormCommand;
    private Command backFormCommand;
    private Command cancelAtBeginningFormCommand;
    private Alert confirmationAlert;
    private Command saveFormCommand;
    private Command discardFormCommand;
    private Alert formSaved = new Alert("Info", "Form data saved", null, AlertType.INFO);

    private final int STEP_FIRST = 0;
    private final int STEP_LAST = 2;
    private final int STEP_MIDDLE = 1;
    /**
     * The RegistrationScreen constructor.
     * @param midlet the midlet used for getting
     */
    public CollectScreen (MIDlet midlet) {
        this.midlet = (RefugeesUnited)midlet;
        backFormCommand = new Command("Previous", Command.SCREEN, 0);
        cancelAtBeginningFormCommand = new Command("Exit", Command.OK, 0);
        nextFormCommand = new Command("Next", Command.BACK, 1);

    }

    //<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
    //</editor-fold>//GEN-END:|methods|0|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
    /**
     * Initilizes the application.
     * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
     */
    private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
    }//GEN-BEGIN:|0-initialize|2|
    //</editor-fold>//GEN-END:|0-initialize|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|2-switchDisplayable|0|2-preSwitch
    /**
     * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
     * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|2-switchDisplayable|0|2-preSwitch
        // write pre-switch user code here
        Display display = getDisplay();//GEN-BEGIN:|2-switchDisplayable|1|2-postSwitch
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }//GEN-END:|2-switchDisplayable|1|2-postSwitch
        // write post-switch user code here
    }//GEN-BEGIN:|2-switchDisplayable|2|
    //</editor-fold>//GEN-END:|2-switchDisplayable|2|
    //</editor-fold>
    //</editor-fold>
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: CollectDataForm ">//GEN-BEGIN:|11-getter|0|11-preInit
    /**
     * Returns an initiliazed instance of CollectDataForm component.
     * @return the initialized component instance
     */
    public Form getCollectDataForm() {
        if (CollectDataForm == null) {//GEN-END:|11-getter|0|11-preInit
            // write pre-init user code here
            CollectDataForm = new Form("Collect Data", new Item[] { });//GEN-BEGIN:|11-getter|1|11-postInit
            CollectDataForm.addCommand(getBackCommand());
            CollectDataForm.setCommandListener(this);//GEN-END:|11-getter|1|11-postInit
            // write post-init user code here
        }//GEN-BEGIN:|11-getter|2|
        return CollectDataForm;
    }
    //</editor-fold>//GEN-END:|11-getter|2|







    //<editor-fold defaultstate="collapsed" desc=" Generated Method: display ">//GEN-BEGIN:|16-entry|0|17-preAction
    /**
     * Performs an action assigned to the display entry-point.
     */
    public void display() {//GEN-END:|16-entry|0|17-preAction
        // write pre-action user code here
//GEN-LINE:|16-entry|1|17-postAction
        // write post-action user code here
        // get form content
        this.midlet.getFormController().generateSteps();
        AbstractFormWidget content = this.midlet.getFormController().getCurrentStep();
        showContent(content, STEP_FIRST);
    }//GEN-BEGIN:|16-entry|2|
    //</editor-fold>//GEN-END:|16-entry|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|4-commandAction|0|4-preCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a particular displayable.
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {//GEN-END:|4-commandAction|0|4-preCommandAction
        // write pre-action user code here
        if (displayable == CollectDataForm) {//GEN-BEGIN:|4-commandAction|1|21-preAction
            if (command == backCommand) {//GEN-END:|4-commandAction|1|21-preAction
                // write pre-action user code here
                this.midlet.backToMenu();//GEN-LINE:|4-commandAction|2|21-postAction
                // write post-action user code here
            }//GEN-BEGIN:|4-commandAction|3|4-postCommandAction
        }//GEN-END:|4-commandAction|3|4-postCommandAction
        // write post-action user code here
        if(command == backCommand){
            this.midlet.backToMenu();
        }
        if(command == nextFormCommand){
            saveAnswer((AbstractFormWidget)getDisplay().getCurrent());
            AbstractFormWidget content = this.midlet.getFormController().getNextStep();
            if(content != null){
                showContent(content, STEP_MIDDLE);
            }else{
                showConfirmationAlert();
            }
        }
        if(command == backFormCommand){
            saveAnswer((AbstractFormWidget)getDisplay().getCurrent());
            AbstractFormWidget content = this.midlet.getFormController().getPreviousStep();
            if(this.midlet.getFormController().getCurrentStepIndex() == 0){
                showContent(content, STEP_FIRST);
            }else{
                showContent(content, STEP_MIDDLE);
            }
        }
        if(command == cancelAtBeginningFormCommand){
            this.midlet.backToMenu();
        }
        if(command == saveFormCommand){
            this.midlet.getFormController().saveCompleteForm();
            switchDisplayable(formSaved, getCollectDataForm());
            this.midlet.backToMenu();
        }
        if(command == discardFormCommand){
            AbstractFormWidget content = this.midlet.getFormController().getCurrentStep();
            showContent(content, STEP_MIDDLE);
        }

    }//GEN-BEGIN:|4-commandAction|4|
    //</editor-fold>//GEN-END:|4-commandAction|4|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: backCommand ">//GEN-BEGIN:|20-getter|0|20-preInit
    /**
     * Returns an initiliazed instance of backCommand component.
     * @return the initialized component instance
     */
    public Command getBackCommand() {
        if (backCommand == null) {//GEN-END:|20-getter|0|20-preInit
            // write pre-init user code here
            backCommand = new Command("Back", Command.BACK, 0);//GEN-LINE:|20-getter|1|20-postInit
            // write post-init user code here
        }//GEN-BEGIN:|20-getter|2|
        return backCommand;
    }
    //</editor-fold>//GEN-END:|20-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: backFromCamera ">//GEN-BEGIN:|22-entry|0|23-preAction
    /**
     * Performs an action assigned to the backFromCamera entry-point.
     */
    public void backFromCamera() {//GEN-END:|22-entry|0|23-preAction
        // write pre-action user code here
//GEN-LINE:|22-entry|1|23-postAction
        // write post-action user code here

    }//GEN-BEGIN:|22-entry|2|
    //</editor-fold>//GEN-END:|22-entry|2|





    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay () {
        return Display.getDisplay(midlet);
    }

    /**
     * Exits MIDlet.
     * Note you have to implement proper MIDlet destroying.
     */
    public void exitMIDlet() {
        switchDisplayable (null, null);
        // midlet.destroyApp(true);
        midlet.notifyDestroyed();
    }

    public void commandAction(Command cmnd, Item item) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    private void showContent(AbstractFormWidget displayable, int stepType){
        if(!displayable.getInitialized()){
            switch(stepType){
                case STEP_FIRST:
                    displayable.addCommand(cancelAtBeginningFormCommand);
                    displayable.addCommand(nextFormCommand);
                    break;
                case STEP_LAST:
                    displayable.addCommand(nextFormCommand);
                    displayable.addCommand(backFormCommand);
                    break;
                default:
                    displayable.addCommand(nextFormCommand);
                    displayable.addCommand(backFormCommand);
                    break;
            }
            displayable.initialize();
        }
        displayable.setCommandListener(this);
        switchDisplayable(null, displayable);
    }

    private void saveAnswer(AbstractFormWidget content){
        content.saveAnswer();
    }

    private void showConfirmationAlert(){
        confirmationAlert = new Alert("Confirmation");
        confirmationAlert.setString("Do you want to save Registration Form?");
        confirmationAlert.setType(AlertType.CONFIRMATION);
        confirmationAlert.setTimeout(Alert.FOREVER);
        saveFormCommand = new Command("Yes", Command.OK, 0);
        discardFormCommand = new Command("No", Command.EXIT, 0);
        confirmationAlert.addCommand(saveFormCommand);
        confirmationAlert.addCommand(discardFormCommand);
        confirmationAlert.setCommandListener(this);
        showAlert(confirmationAlert);
    }

    private void showAlert(Alert a){
        switchDisplayable(a, getDisplay().getCurrent());
    }

}
